package GUI;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import users.Author;
import users.ProgramChair;
import users.Reviewer;
import users.User;

import conference.Conference;
import conference.ConferenceIO;
import conference.TextParse;

/**
 * The start GUI for selecting a conference, user and role
 * @author Taylor Zielske
 * revised by: Matt Minch
 * @version November 30, 2011
 */
public class ConferenceFrame extends JFrame {

	private static final long serialVersionUID = 1L;
	/**
	 * Creates the Frame for the EZConference Start up
	 * @throws UnsupportedLookAndFeelException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws ClassNotFoundException 
	 */
	private Conference my_conf;
	private User my_user;
	private List<User> my_user_list;

	public ConferenceFrame() {
		super("EZConference - by Group 6 Awesome");
		this.setPreferredSize(new Dimension(700,400));
		this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		this.setLayout(new BorderLayout());

	}
	/**
	 * Starts the GUI for EZConference Start up
	 * @throws IOException 
	 */
	public void start() throws IOException{
		my_user = new Author("Test");
		JPanel conference= new JPanel();
		conference.setLayout(new BorderLayout());
		ImageIcon icon = new ImageIcon("images" +
				File.separator + "Logo.png"); 
		ImageIcon titleicon = new ImageIcon("images" +
				File.separator + "title.png");
		JLabel logolabel = new JLabel(); 
		JLabel titlelabel = new JLabel();
		logolabel.setIcon(icon); 
		titlelabel.setIcon(titleicon);
		JPanel logopanel = new JPanel();
		JPanel titlepanel = new JPanel();
		logopanel.add(logolabel);
		titlepanel.add(titlelabel);
		conference.add(titlepanel, BorderLayout.NORTH);
		conference.add(logopanel, BorderLayout.CENTER); 
		final JPanel dropdowns = new JPanel(new GridLayout());
		final JComboBox conferencechooser = new JComboBox();
		final JComboBox userchooser = new JComboBox();
		final JComboBox rolechooser = new JComboBox();
		final ImageIcon submiticon = new ImageIcon("images" +
				File.separator + "submit.jpg");
		final JLabel submit = new JLabel(submiticon);
		submit.setVisible(false);
		//conference list
		//for each unique conference add the name to the chooser
		final TextParse tp = new TextParse(new File(System.getProperty("user.dir") + File.separator + "config.txt"));
		final List<String> conferencelist = new ArrayList<String>();
		for (String[] t : tp.readUserFile()){
			if(!conferencelist.contains(t[1])){
				conferencelist.add(t[1]);
			}
		}
		conferencechooser.addItem("Choose Conference");
		for (String s : conferencelist){
			conferencechooser.addItem(s);
		}
		conferencechooser.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (conferencechooser.getSelectedIndex() != 0){
					my_user_list = new ArrayList<User>();
					Conference conf = null;
					File testFolder = new File(TextParse.getFileLoc(),conferencechooser.getSelectedItem().toString());
					if (!testFolder.exists()) {
						testFolder.mkdir();
					}
					conf = ConferenceIO.loadConference(TextParse.getFileLoc(), conferencechooser.getSelectedItem().toString());
					if (conf == null){
						conf = new Conference(tp.getChair(conferencechooser.getSelectedItem().toString()),
								conferencechooser.getSelectedItem().toString(), null, null,
								tp.getUsers(conferencechooser.getSelectedItem().toString()));
						ConferenceIO.saveConference(TextParse.getFileLoc(), conf);
					}
					
					my_conf = conf;
					List<String> userList = new ArrayList<String>();
					for (User t : tp.getUsers(my_conf.getConfName())){
						if(!userList.contains(t.getName())){
							userList.add(t.getName());
						}
						my_user_list.add(t);
					}
					my_user_list.add(new Author("New User"));
					userchooser.removeAllItems();
					rolechooser.removeAllItems();
					userchooser.addItem("Choose User");
					for(String user: userList){
						userchooser.addItem(user);
					}
					userchooser.addItem("New User");
					userchooser.setVisible(true);
				}else {
					userchooser.setVisible(false);
					rolechooser.setVisible(false);
					submit.setVisible(false);
				}
			}
		});
		userchooser.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (userchooser.getSelectedIndex() != 0 && userchooser.getSelectedItem() != null){
					List<User> user_list = new ArrayList<User>();
					for(User u: my_user_list){
						user_list.add(u);
					}

					for (User u: user_list){
						if (!(u.getName().equals(userchooser.getSelectedItem().toString()))){
							my_user_list.remove(u);
						}
					}
					rolechooser.removeAllItems();
					rolechooser.addItem("Choose Role");
					List<String> roles = tp.getRoles(userchooser.getSelectedItem().toString(),
							conferencechooser.getSelectedItem().toString());
					for (String s: roles)
					{
						rolechooser.addItem(s);
					}
					if (!roles.contains("Author"))
					{
						rolechooser.addItem("Author");
					}
					rolechooser.setVisible(true);
					repaint();
				}		    	  
				else {
					rolechooser.setVisible(false);
					submit.setVisible(false);

				}
			}
		});
		rolechooser.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// show submit button
				if (rolechooser.getSelectedIndex() != 0){
					submit.setVisible(true);
				}		    	  
				else {
					submit.setVisible(false);

				}
			}
		});
		submit.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				// set conference, user and role
				if(rolechooser.getSelectedItem().toString().compareToIgnoreCase("Author") == 0){
					boolean newauthor = true;
					for (User u :my_user_list){
						if(u instanceof Author){
							my_user = (Author) u;
							newauthor = false;
						}
					}
					if (newauthor){
						my_user = new Author(userchooser.getSelectedItem().toString());
						try {
							my_conf.addUser(my_user);
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
				}else if(rolechooser.getSelectedItem().toString().compareToIgnoreCase("Reviewer") == 0){
					for (User u :my_user_list){
						if(u instanceof Reviewer){
							my_user = (Reviewer) u;
						}
					}
				}else if (rolechooser.getSelectedItem().toString().compareToIgnoreCase("Program Chair") == 0){
					for (User u :my_user_list){
						if(u instanceof ProgramChair){
							my_user = (ProgramChair) u;
						}
					}
				}
				if(my_user.getName() != "New User"){
					TabbedConfFrame a = new TabbedConfFrame(my_conf, my_user, TextParse.getFileLoc(), conferencelist);
					a.start();
				}else{
					final JFrame setusername = new JFrame("Set Username");
					setusername.setPreferredSize(new Dimension(300,100));
					setusername.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
					JPanel panel = new JPanel(new GridLayout(0,1));
					setusername.add(panel);
					setusername.pack();
					setusername.setLocationRelativeTo(null);
					setusername.setVisible(true);
					final JTextField username = new JTextField();
					JLabel format = new JLabel("Enter a username");
					JButton button = new JButton("OK");
					panel.add(format);
					panel.add(username);
					panel.add(button);
					button.addActionListener(new ActionListener(){
						public void actionPerformed(ActionEvent e) {
								my_user = (Author)my_user;
								my_user.setName(username.getText());
								boolean vaild = false;
								try {
									vaild = my_conf.addUser(my_user);
								} catch (IOException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
								if (vaild){
									setusername.dispose();
									TabbedConfFrame a = new TabbedConfFrame(my_conf, my_user, TextParse.getFileLoc(), conferencelist);
									a.start();
								}else{
									JOptionPane.showMessageDialog(setusername, "This username is already used by another user in" +
											" the system, please enter a different username", "Invalid Username", JOptionPane.ERROR_MESSAGE);
								}
							}

						});

					}
					if (my_user instanceof ProgramChair && (my_conf.getManuDate() == null || my_conf.getRevDate() == null)){
						final JFrame setdeadlines = new JFrame("Set " + my_conf.getConfName() + "'s Deadlines");
						setdeadlines.setPreferredSize(new Dimension(300,200));
						setdeadlines.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
						JPanel panel = new JPanel(new GridLayout(0,1));
						setdeadlines.add(panel);
						setdeadlines.pack();
						setdeadlines.setLocationRelativeTo(null);
						setdeadlines.setVisible(true);
						final JTextField manudeadline = new JTextField();
						final JTextField reviewdeadline = new JTextField();
						JLabel title = new JLabel("Set " + my_conf.getConfName() + "'s Deadlines");
						JLabel format = new JLabel("Enter in format dd/mm/yyyy");
						JLabel manu = new JLabel("Manuscript Deadline");
						JLabel review = new JLabel("Review Deadline");
						JButton button = new JButton("OK");
						panel.add(title);
						panel.add(format);
						panel.add(manu);
						panel.add(manudeadline);
						panel.add(review);
						panel.add(reviewdeadline);
						panel.add(button);
						button.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent e) {
								manudeadline.getText();
								reviewdeadline.getText();
								boolean correctmanu = false;
								boolean correctreview = false;
								DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
								try {
									Date d = df.parse(manudeadline.getText());
									my_conf.setManuDate(d);
									correctmanu = true;
								} catch (ParseException e1) {
									correctmanu = false;
									JOptionPane.showMessageDialog(setdeadlines, "Invalid Manuscript Deadline Date, " +
											"please use dd/mm/yyyy format", "Invalid Deadline Date", JOptionPane.ERROR_MESSAGE);
								}
								try {
									Date d = df.parse(reviewdeadline.getText());
									my_conf.setRevDate(d);
									correctreview = true;
								} catch (ParseException e1) {
									correctreview = false;
									JOptionPane.showMessageDialog(setdeadlines, "Invalid Review Deadline Date, " +
											"please use dd/mm/yyyy format", "Invalid Deadline Date", JOptionPane.ERROR_MESSAGE);
								}
								if(correctmanu && correctreview){
									ConferenceIO.saveConference(TextParse.getFileLoc(), my_conf);
									setdeadlines.dispose();
								}
							}
						});
					}
					close();
				}
			});
		userchooser.setVisible(false);
		rolechooser.setVisible(false);
		dropdowns.add(conferencechooser);
		dropdowns.add(userchooser);
		dropdowns.add(rolechooser);
		dropdowns.add(submit);
		JPanel choosers = new JPanel(new BorderLayout());
		JPanel blank = new JPanel();
		choosers.add(dropdowns, BorderLayout.NORTH);
		choosers.add(blank, BorderLayout.CENTER);
		conference.add(choosers, BorderLayout.SOUTH);
		this.add(conference, BorderLayout.CENTER);
		this.pack();
		setLocationRelativeTo(null);
		this.setVisible(true);
	}
	/**
	 * Closes the frame
	 */
	private void close(){
		this.dispose();
	}
}
